//
//  ModuleListVC.m
//  Project
//
//  Created by 冯东辉 on 2018/9/19.
//  Copyright © 2018年 FengDongHui. All rights reserved.
//

#import "ModuleListVC.h"
#import "CityTableView.h"
#import "MJRefresh.h"
#import "ModuelCell.h"
#import "ModuleDetailVC.h"
#import "CityDetailVC.h"
#import "ZhiBiaoDetailVC.h"

@interface ModuleListVC () <CityChooseCallBack, UIGestureRecognizerDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *data;

@property (nonatomic, strong) NSMutableArray *colorData;
@property (nonatomic, strong) NSArray *fourColorData;

@property (nonatomic, assign) NSInteger pageNo;

@property (nonatomic, strong) UIButton *rightBtn;
@property (nonatomic, strong) NSArray *city_data;

// 城市展示图
@property (nonatomic, strong) UIView *cityBaseV;
@property (nonatomic, strong) CityTableView *cityTable;

@end

@implementation ModuleListVC

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.navTitleL.text = _moduleName;
    [self createBlueNavigationBar:YES];
    
    self.view.backgroundColor = UICOLOR_HEX(0xffEDEEEF);
    
    _fourColorData = @[@[UICOLOR_HEX(0xff259df7), UICOLOR_HEX(0xff9a78e2)], @[UICOLOR_HEX(0xffa161d7), UICOLOR_HEX(0xffdd72b4)], @[UICOLOR_HEX(0xff3ba9c2), UICOLOR_HEX(0xff41b8b6)], @[UICOLOR_HEX(0xfffd7274), UICOLOR_HEX(0xfff1a953)]];
    
    _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_rightBtn setTitle:self.cityName forState:UIControlStateNormal];
    [_rightBtn setTitleColor:UICOLOR_HEX(0xffffffff) forState:UIControlStateNormal];
    [_rightBtn addTarget:self action:@selector(showAllCity) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_rightBtn];
    
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
    [self initSubViews];
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
}

#pragma mark - init
- (void)initSubViews {
    
    [self.view addSubview:self.tableView];
}

- (UITableView *)tableView {
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(10, SafeAreaTopHeight, GET_SCREEN_WIDTH()-20, GET_SCREEN_HEIGHT()-SafeAreaTopHeight)];
        _tableView.backgroundColor = UICOLOR_HEX(0xffEDEEEF);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.showsVerticalScrollIndicator = NO;
        
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        
        header.lastUpdatedTimeLabel.hidden = YES;
        // 设置文字
        [header setTitle:@"下拉刷新" forState:MJRefreshStateIdle];
        [header setTitle:@"释放刷新" forState:MJRefreshStatePulling];
        [header setTitle:@"加载中..." forState:MJRefreshStateRefreshing];
        
        // 马上进入刷新状态
        [header beginRefreshing];
        
        // 设置刷新控件
        self.tableView.mj_header = header;
        
        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        [footer setTitle:@"点击或拖动刷新" forState:MJRefreshStateIdle];
        [footer setTitle:@"加载更多..." forState:MJRefreshStateRefreshing];
        [footer setTitle:@"无更多数据" forState:MJRefreshStateNoMoreData];
        self.tableView.mj_footer = footer;
        [self.tableView.mj_footer setHidden:YES];
        
    }
    return _tableView;
}

- (void)loadNewData {
    
    _pageNo = 1;
    
    [[ProjectApi instance] getModuleListDataWithCityName:_cityName type:_type sdim_ID:_sdim_ID page:[NSString stringWithFormat:@"%ld", _pageNo] callBack:^(NetModel *object) {
        
        [self.tableView.mj_header endRefreshing];
        
        if (object.isSuccessed) {
            
            
            [self.data removeAllObjects];
            self.data = nil;
            self.data = [NSMutableArray arrayWithArray:object.service];
            
            [self.colorData removeAllObjects];
            self.colorData = nil;
            self.colorData = [[NSMutableArray alloc] init];
            
            NSInteger index = 0;
            
            for (int i = 0; i < [self.data count]; i++) {
                
                if (index%4 == 0) {
                    
                    index = 0;
                }
                
                [self.colorData addObject:self.fourColorData[index]];
                
                index++;
            }
            
            if (self.data && [self.data count] > 0) {
                
                if ([self.data count] < 5) {
                    self.tableView.mj_footer.hidden = YES;
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }else {
                    [self.tableView.mj_footer setHidden:NO];
                    [self.tableView.mj_footer resetNoMoreData];
                }
                
            }else {
                
                self.tableView.mj_footer.hidden = YES;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
                
                [SVProgressHUD showInfoWithStatus:@"暂无数据"];
                [SVProgressHUD dismissWithDelay:1.5f];
            }
            
            [self.tableView reloadData];
            
        }else {
            
            [SVProgressHUD showErrorWithStatus:@"网络连接失败"];
            [SVProgressHUD dismissWithDelay:1.5f];
        }

    }];
}

- (void)loadMoreData {
    
    _pageNo = _pageNo+1;
    
    [[ProjectApi instance] getModuleListDataWithCityName:_cityName type:_type sdim_ID:_sdim_ID page:[NSString stringWithFormat:@"%ld", _pageNo] callBack:^(NetModel *object) {
        
        [self.tableView.mj_footer endRefreshing];
        
        if (object.isSuccessed) {
            
            NSArray *array = [NSArray arrayWithArray:object.service];

            if (array && [array count] > 0) {
                
                [self.tableView.mj_footer endRefreshing];
                
                for (int i = 0; i < [array count]; i++) {
                    
                    [self.data addObject:array[i]];
                }
                
                [self.colorData removeAllObjects];
                self.colorData = nil;
                self.colorData = [[NSMutableArray alloc] init];
                
                NSInteger index = 0;
                
                for (int i = 0; i < [self.data count]; i++) {
                    
                    if (index%4 == 0) {
                        
                        index = 0;
                    }
                    
                    [self.colorData addObject:self.fourColorData[index]];
                    
                    index++;
                }
                
            }else {
                
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
                
                [SVProgressHUD showInfoWithStatus:@"暂无数据"];
                [SVProgressHUD dismissWithDelay:1.5f];
            }
            
            [self.tableView reloadData];
            
        }else {
            
            self.pageNo = self.pageNo-1;
            [SVProgressHUD showErrorWithStatus:@"数据加载失败"];
            [SVProgressHUD dismissWithDelay:1.5f];
        }
        
    }];
}

#pragma mark - tableView delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return tableView.height/5.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    NSDictionary *dic = _data[indexPath.row];
    
    if ([_moduleName isEqualToString:@"业务发展"]) {
        
        ZhiBiaoDetailVC *vc = [[ZhiBiaoDetailVC alloc] init];
        vc.moduleName = [NSString stringWithFormat:@"%@", dic[@"inD_Name"]];
        vc.cityName = _cityName;
        vc.s_id = dic[@"s_id"];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else {
        
        if ([_cityName isEqualToString:@"全省"]) {
            
            ModuleDetailVC *detailVC = [[ModuleDetailVC alloc] init];
            detailVC.moduleName = [NSString stringWithFormat:@"%@", dic[@"inD_Name"]];
            detailVC.s_id = [NSString stringWithFormat:@"%@", dic[@"s_id"]];
            detailVC.cityName = _cityName;
            [self.navigationController pushViewController:detailVC animated:YES];
            
        }else {
            
            CityDetailVC *vc = [[CityDetailVC alloc] init];
            vc.moduleName = _moduleName;
            vc.cityName = _cityName;
            vc.s_id = dic[@"s_id"];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

#pragma mark - tableView dataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [_data count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifierA = @"module_list_cell";
    
    ModuelCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierA];
    
    if (cell == nil) {
        
        cell = [[ModuelCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierA];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        cell.contentView.backgroundColor = [UIColor clearColor];
    }
    
//    CAGradientLayer *colorLayer;
//
//    for (id layer in cell.baseView.layer.sublayers) {
//
//        if ([layer isKindOfClass:[CAGradientLayer class]]) {
//            colorLayer = layer;
//            break;
//        }
//    }
//
//    [ProjectTools setLayerJianBianWithBenginColor:_colorData[indexPath.row][0] endColor:_colorData[indexPath.row][1] layer:colorLayer];
    
    for (id layer in cell.baseView.layer.sublayers) {
        
        if ([layer isKindOfClass:[CAGradientLayer class]]) {
            [layer removeFromSuperlayer];
            break;
        }
    }
    
    [cell.baseView.layer insertSublayer:[ProjectTools setModuleListJianBianWithBenginColor:_colorData[indexPath.row][0] endColor:_colorData[indexPath.row][1] frame:cell.baseView.bounds] atIndex:0];
    
    [cell reloadSubViewWithData:_data indexPath:indexPath];
    
    [cell.collect_btn addTarget:self action:@selector(collectOrCancel:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}


#pragma mark - 收藏/取消收藏
- (void)collectOrCancel:(UIButton *)btn {
    
    btn.userInteractionEnabled = NO;
    
    NSInteger tag = btn.tag - 999;
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:_data[tag]];
    
    // 是否收藏
    NSInteger inD_FAV = [dic[@"inD_FAV"] integerValue];
    
    NSString *dimid = [NSString stringWithFormat:@"%@", dic[@"sdim_ID"]];
    NSString *incatorname = [NSString stringWithFormat:@"%@", dic[@"s_id"]];
    
    if (inD_FAV == 0) {
        
        // 去收藏
        [[ProjectApi instance] collectHandleWithFlag:@"1" dimid:dimid incatorname:incatorname callBack:^(NetModel *object) {
            
            btn.userInteractionEnabled = YES;
            
            if (object.isSuccessed) {
                
                [dic setObject:@"1" forKey:@"inD_FAV"];
                [self.data removeObjectAtIndex:tag];
                [self.data insertObject:dic atIndex:tag];
                
                
                [self.tableView reloadData];
                
                [SVProgressHUD showSuccessWithStatus:@"收藏成功"];
                [SVProgressHUD dismissWithDelay:1.5f];
                
            }else {
                
                [SVProgressHUD showErrorWithStatus:@"收藏失败"];
                [SVProgressHUD dismissWithDelay:1.5f];
            }
        }];
        
    }else {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确定取消收藏该指标？" preferredStyle:UIAlertControllerStyleAlert];
        
        // 取消
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            btn.userInteractionEnabled = YES;
        }];
        
        [alertController addAction:cancelAction];
        
        // 确定
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            // 取消收藏
            [[ProjectApi instance] collectHandleWithFlag:@"2" dimid:dimid incatorname:incatorname callBack:^(NetModel *object) {
                
                btn.userInteractionEnabled = YES;
                
                if (object.isSuccessed) {
                    
                    [dic setObject:@"0" forKey:@"inD_FAV"];
                    [self.data removeObjectAtIndex:tag];
                    [self.data insertObject:dic atIndex:tag];
                    
                    
                    [self.tableView reloadData];
                    
                    [SVProgressHUD showSuccessWithStatus:@"已取消收藏"];
                    [SVProgressHUD dismissWithDelay:1.5f];
                    
                }else {
                    
                    [SVProgressHUD showErrorWithStatus:@"取消收藏失败"];
                    [SVProgressHUD dismissWithDelay:1.5f];
                }
            }];
        }];
        
        [alertController addAction:confirmAction];
        
        // 弹出
        [self presentViewController:alertController animated:YES completion:^{
        }];
    }
}

#pragma mark - 展示城市选择
- (void)showAllCity {
    
    _city_data = [[NSUserDefaults standardUserDefaults] objectForKey:USER_CITY_DATA];
    
    if (_city_data && [_city_data count] > 0) {
        
        [self creatCityChooseView];
        
    }else {
        
        // 获取用户ID拥有的地市权限
        [SVProgressHUD showWithStatus:@"加载中..."];
        
        [[ProjectApi instance] getUserCityDataCallBack:^(NetModel *object) {
            
            if (object.isSuccessed) {
                
                self.city_data = [NSArray arrayWithArray:object.service];
                
                [[NSUserDefaults standardUserDefaults] setObject:self.city_data forKey:USER_CITY_DATA];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                [SVProgressHUD dismiss];
                
                [self creatCityChooseView];
                
            }else {
                
                [SVProgressHUD showErrorWithStatus:@"地址加载失败"];
                [SVProgressHUD dismissWithDelay:1.5f];
            }
        }];
    }
}


#pragma mark - 创建城市选择视图
- (void)creatCityChooseView {
    
    _cityBaseV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, GET_SCREEN_WIDTH(), GET_SCREEN_HEIGHT())];
    _cityBaseV.backgroundColor = [UIColor clearColor];
    [self.view.window addSubview:_cityBaseV];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidCityBaseView)];
    tap.delegate = self;
    [_cityBaseV addGestureRecognizer:tap];
    
    CGFloat table_height = 40*[_city_data count];
    
    if (table_height > GET_SCREEN_HEIGHT()*2/3.0f) {
        
        table_height = GET_SCREEN_HEIGHT()*2/3.0f;
    }
    
    _cityTable = [[CityTableView alloc] initWithFrame:CGRectMake(GET_SCREEN_WIDTH()-80, SafeAreaTopHeight, 80, table_height) style:UITableViewStylePlain data:_city_data];
    _cityTable.city_delegate = self;
    [_cityBaseV addSubview:_cityTable];
}

#pragma mark - 隐藏城市展示图
- (void)hidCityBaseView {
    
    _cityBaseV.hidden = YES;
}

#pragma mark - 城市选择回调
- (void)cityChooseCallBack:(NSDictionary *)city_dic {
    
    // 隐藏展示图
    [self hidCityBaseView];
    
    // 选择的城市名称
    NSString *chooseCityName = [NSString stringWithFormat:@"%@", city_dic[@"cityname"]];
    
    if ([chooseCityName isEqualToString:_cityName]) {
        return;
    }
    
    _cityName = chooseCityName;
    
    [_rightBtn setTitle:self.cityName forState:UIControlStateNormal];
    
    [self.tableView.mj_header beginRefreshing];
    
    [self loadNewData];
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    
    //判断如果点击的是tableView的cell，就把手势给关闭了
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        
        return NO;
    }
    
    return YES;
}


@end
